package com.example.week07.test;

import com.example.week07.utils.RandomValue;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.concurrent.CountDownLatch;

/**
 * hikari连接
 */
public class HikariTest2 {

    private static final String driverClassName = "com.mysql.cj.jdbc.Driver";    //启动驱动
    private static final String url = "jdbc:mysql://127.0.0.1:3306/training_camp?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL&rewriteBatchedStatements=true";    //设置连接路径
    private static final String username = "root";    //数据库用户名
    private static final String password = "12345678";    //数据库连接密码


    public static void main(String[] args) throws Exception {
        long time = System.currentTimeMillis();

        /**
         * 批量新增
         */
        CountDownLatch latch = new CountDownLatch(3);
        new Thread(() -> {
            batchAdd();
            latch.countDown();
        }).start();
        new Thread(() -> {
            batchAdd();
            latch.countDown();
        }).start();
        new Thread(() -> {
            batchAdd();
            latch.countDown();
        }).start();


        latch.await();


        System.out.println("总耗时===" + (System.currentTimeMillis() - time) + "ms");
    }

    private static void batchAdd() {
        System.out.println("-------------开始批量新增------------");
        Connection con = null;        //连接
        PreparedStatement pstmt = null;    //使用预编译语句
        ResultSet rs = null;    //获取的结果集
        try {
            Class.forName(driverClassName); //执行驱动
            con = DriverManager.getConnection(url, username, password); //获取连接

            con.setAutoCommit(false); //设置手动提交

            String sql = "INSERT INTO user (name,phone) VALUES(?,?)"; //设置的预编译语句格式
            pstmt = con.prepareStatement(sql);
            for (int i = 0; i < 300000; i++) {
                pstmt.setString(1, RandomValue.getTel());
                pstmt.setString(2, RandomValue.getChineseName());
                // 添加到批次
                pstmt.addBatch();
            }
            pstmt.executeBatch();//提交批处理
            con.commit();//执行
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //关闭资源,倒关
            try {
                if (rs != null) rs.close();
                if (pstmt != null) pstmt.close();
                if (con != null) con.close();  //必须要关
            } catch (Exception e) {
            }
        }
    }
}
